<template>
  <transition>
  <div class="store-settled-in">
    <section class="app-main">
      <mt-field label="企业名称" placeholder="请输入企业名称" v-model="post.storeName"></mt-field>
      <!--<mt-cell-->
        <!--title="门店类型" class="mint-field">-->
        <!--<select v-model="post.storeType" class="select-operator">-->
          <!--<option value="3501">汽车玻璃门店</option>-->
          <!--<option value="3505">汽车修理厂</option>-->
        <!--</select>-->
      <!--</mt-cell>-->
      <mt-field label="联系人" placeholder="请输入联系人" v-model="post.linkName"></mt-field>
      <mt-field label="手机号码" placeholder="请输入手机号码" v-model="post.linkPhone"></mt-field>
      <mt-field label="验证码" placeholder="请输入验证码" v-model="post.code">
        <mt-button type="danger" class="button-send-code" :class="{disabled:validCode==false}" @click="handleGetCode">{{getCodeTitle}}</mt-button>
      </mt-field>

      <mt-field label="所在地区" placeholder="请选择所在地区" v-model="post.area" readonly="readonly" @click.native="handleSelectAddress"></mt-field>
      <mt-field label="详细地址" placeholder="请输入详细地址" v-model="post.address"></mt-field>

      <mt-cell
        title="营业执照" class="mint-field mint-field-img">
        <dl class="img-upload-content me-row">
          <dd class="item me-col-3" v-for="(item,index) in files" v-if="item.fileLocate=='营业执照'">
            <span class="iconfont icon-shanchu" @click="handleDelImg(index,item)"></span>
            <img class="img" :src="item.src" @click="handleCheckPic(index)"/>
          </dd>
          <dd class="item me-col-3 item-add " @click="handleSelectImg('营业执照')">
            <span class="iconfont add-img icon-jiahao"></span>
          </dd>
        </dl>
      </mt-cell>
      <mt-cell
        title="实体门店图" class="mint-field mint-field-img">
        <dl class="img-upload-content me-row">
          <dd class="item me-col-3" v-for="(item,index) in files" v-if="item.fileLocate=='实体门店图'">
            <span class="iconfont icon-shanchu" @click="handleDelImg(index,item)"></span>
            <img class="img" :src="item.src" @click="handleCheckPic(index)"/>
          </dd>
          <dd class="item me-col-3 item-add" @click="handleSelectImg('实体门店图')">
            <span class="iconfont add-img icon-jiahao"></span>
          </dd>
        </dl>
      </mt-cell>
      <!--弹窗-选择门店地址-->
      <mt-popup
        v-model="popupShow"
        position="bottom" class="popup-address">
        <mt-picker :slots="addressSlots" class="picker" @change="onAddressChange" :visible-item-count="5" ></mt-picker>
        <div class="button-content">
          <mt-button type="danger" @click="popupShow=false">确认</mt-button>
        </div>
      </mt-popup>
      <!--{{post}}-->
      <!--弹窗-选择门店地址-->
      <div class="button-content button-content-apply">
        <mt-button type="danger" @click="handleApply">申请入驻</mt-button>
      </div>
      <mt-popup
        v-model="popupApplyCorrect"
        position="middle" class="popup-apply-correct">
        <span class="iconfont icon-chenggong"></span>
        <div class="correct-tips">您已提交成功，请耐心等待审核！</div>
      </mt-popup>
    </section>
  </div>
    </transition>
</template>

<script>
  import { Header,Cell,Field,Button,Toast ,Indicator} from 'mint-ui';
  import s from '../../../static/address.json'
//  Vue.component(Header.name, Header);
export default {
  components:{
    Header,
    Cell,
  },
  data () {
    return {
      popupApplyCorrect:false,
      wxConfig:'',
      getCodeTitle:'获取验证码',
      validCode:true,
      files:[],
      popupShow:false,
      addressSlots: [
        {
          flex: 1,
          defaultIndex: 1,
          values: Object.keys(s),
          className: 'slot1',
          textAlign: 'center'
        }, {
          divider: true,
          content: '-',
          className: 'slot2'
        }, {
          flex: 1,
          values: [],
          className: 'slot3',
          textAlign: 'center'
        }, {
          divider: true,
          content: '-',
          className: 'slot4'
        }, {
          flex: 1,
          values: [],
          className: 'slot5',
          textAlign: 'center'
        }
      ],
      addressProvince: '省',
      addressCity: '市',
      addressXian: '区',
      addressStreet: '街道',
      mediaAttr:[],
      myUploads:'',
      accessToken:'',
      post:{
        storeName:'',
        linkName:'',
        linkPhone:'',
        code:'',
        area:'',
        address:'',
        storeType:3501,
        licenseImgOss:'',
        shopImgOss:'',
        openId:'',
      },
      url:'',
    }
  },
  watch: {
    'popupShow'(val){
//      if(){
        this.post.area=this.addressProvince+'-'+this.addressCity+'-'+this.addressXian
//      }
    }
  },
  beforeRouteEnter (to, from, next) {
    var u = navigator.userAgent;
    var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
    // XXX: 修复iOS版微信HTML5 History兼容性问题
    if (isiOS && to.path !== location.pathname) {1
      // 此处不可使用location.replace
      location.assign(to.fullPath)
    } else {
      next()
    }
  },

  created(){
    var turl=(location.href).split('/')[2];
    var getCode=(location.href).split('code=')[1];
    var wxcode='';
    if(typeof getCode!=='undefined'){
      wxcode=getCode.split('&')[0];
    }else{
      wxcode=''
    }
    var params = new URLSearchParams();
    params.append('thisUrl',location.href);
    params.append('wxCode',wxcode);
    this.$axios({
      method: 'post',
      url:'gp/bu/oauth!authorizeUser.do',
      data:params,
    }).then((res)=>{
    if(res.data.statusCode==300){
      window.location.href=res.data.object;
    }else if(res.data.statusCode==200){
      this.post.openId=res.data.object.split('-----')[0];
      console.log(res)
    }
  });

    //  调取微信配置接口
    this.url=location.href;
    var params = new URLSearchParams();
    params.append('url',this.url);
    this.$axios({
      method: 'post',
      url:'gp/bu/wechat!getJsapi.do',
      data:params
    }).then((res)=> {
      this.wxConfig=res.data.object;

    this.accessToken=res.data.object.accessToken;
    this.$wx.config({
      beta: true,// 必须这么写，否则wx.invoke调用形式的jsapi会有问题
      debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
      appId: this.wxConfig.appid, // 必填，企业微信的corpID
//      appId: 'wxd05b751d02449b6a', // 必填，企业微信的corpID
      timestamp:this.wxConfig.timestamp, // 必填，生成签名的时间戳
      nonceStr: this.wxConfig.nonceStr, // 必填，生成签名的随机串
      signature: this.wxConfig.signature,// 必填，签名，见附录1
      jsApiList: ['chooseImage','uploadImage','getLocalImgData','downloadImage'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
    });
  });
    this.$nextTick(() => {
      setTimeout(() => {//这个是一个初始化默认值的一个技巧
      this.addressSlots[0].defaultIndex = 0;
    }, 100);
  });
  },
  methods:{
    handleGetCode(){

      var myreg=/^[1][3,4,5,7,8][0-9]{9}$/;
      if(!myreg.test(this.post.linkPhone)){
        Toast({
          message: '请输入有效的手机号码',
          position: 'middle',
          duration: 800
        });
        return false;
      }
      var time=90;
      if (this.validCode) {
        this.validCode=false;
        console.log(1111)
        var params = new URLSearchParams();
        params.append('tel',this.post.linkPhone);
        this.$axios({
          method: 'post',
          url:'gp/bu/commonUtil!sendCode.do',
          data:params
        }).then((res)=>{
          if(res.data.statusCode==200){
          Toast({
            message: '短信发送成功',
            position: 'middle',
            duration:1000
          });

        }else{
          Toast({
            message: res.data.message,
            position: 'middle',
            duration:1000
          });
        }
      })
        this.getCodeTitle=time+"秒重新获取";
        var t=setInterval(()=> {
          time--;
        this.getCodeTitle=time+"秒重新获取";
          if (time==0) {
            clearInterval(t);
            this.getCodeTitle="重新获取"
            this.validCode=true;

          }
        },1000)
      }
    },
    onAddressChange(picker, values) {
      let sheng = Object.keys(s);
      let shi = Object.keys(s[values[0]]);

      let index=shi.indexOf(values[1])
      let xian = s[values[0]][shi[index]];
      this.xianObj = xian;
      picker.setSlotValues(1, shi);
      this.addressProvince = values[0];
      this.addressCity = values[1];
      this.addressXian = values[2];
      if(typeof xian!=='undefined'){
        picker.setSlotValues(2, Object.keys(xian));
      }
      if(this.popupShow==true){
        this.post.area=this.addressProvince+'-'+this.addressCity+'-'+this.addressXian
      }
    },
    handleSelectAddress(){
      this.popupShow=true;
    },
    handleSelectImg(fileLocate){
      this.$wx.ready(()=>{
        var u = navigator.userAgent;
      var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
      var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端

      var _this=this;
      var syncUpload = function(localIds){
        var localId = localIds.pop();
        _this.$wx.uploadImage({
          localId: localId.toString(), // 需要上传的图片的本地ID，由chooseImage接口获得
          isShowProgressTips:1, // 默认为1，显示进度提示
          success: function (res) {
            //res.serverId 返回图片的服务器端ID
            var serverId = res.serverId; // 返回图片的服务器端ID
            const item={
              serverId:res.serverId,
              tag : '',
              fileLocate:fileLocate,
            }
            _this.mediaAttr.push(item);
            if(localIds.length > 0){
              window.setTimeout(function(){
                syncUpload(localIds);
              },100);
            }else{
              window.setTimeout(function(){
                downloadImage(0);
              },100);

            }
          }
        })
      }
      _this.$wx.chooseImage({
        count: 9, // 默认9
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        defaultCameraMode: "batch", //表示进入拍照界面的默认模式，目前有normal与batch两种选择，normal表示普通单拍模式，batch表示连拍模式，不传该参数则为normal模式。（注：用户进入拍照界面仍然可自由切换两种模式）
        success: function (res) {

          var localIds = res.localIds; // 返回选定照片的本地ID列表，

          for(var i=0;i<localIds.length;i++){
            if(isiOS==true){

              _this.$wx.getLocalImgData({
                localId: localIds[i], // 图片的localID
                success: function (res) {
                  var localData = res.localData; // localData是图片的base64数据，可以用img标签显示
                  const item={
                    src:localData,
                    tag : '',
                    fileLocate:fileLocate,
                  };
                  _this.files.push(item);
                  console.log(_this.files);

                },
                fail: function(res) {
                  console.log(res)
                }
              });
            }else{
              const item={
                src:localIds[i],
                tag : '',
                fileLocate:fileLocate,
              };
              _this.files.push(item);
            }


          }

          syncUpload(res.localIds)
          // andriod中localId可以作为img标签的src属性显示图片；
          // 而在IOS中需通过上面的接口getLocalImgData获取图片base64数据，从而用于img标签的显示
        }
      });
    })
    },
    handleDelImg(index,item){
      this.files.splice(index, 1);
      this.mediaAttr.splice(index, 1);
    },
    /**获取oss配置**/
    getOss(){
      let OSS = require('ali-oss');
      this.client = new OSS({
        region: "oss-cn-shenzhen",
        secure: true,//https
        endpoint: 'oss-cn-shenzhen.aliyuncs.com',
        accessKeyId: "LTAIPCNdQvX5yOwc",
        accessKeySecret: "7bReGAz8bc9aJdK4IAz5KW5fnNOzrQ ",
        bucket: 'rmcbapp'
      });
    },
    toBuffer(ab) {
      var buf = new Buffer(ab.byteLength);
      var view = new Uint8Array(ab);
      for (var i = 0; i < buf.length; ++i) {
        buf[i] = view[i];
      }
      return buf;
    },
    handleApply(){
      var myreg=/^[1][3,4,5,6,7,8,9][0-9]{9}$/;
      if(this.post.storeName==''){
        Toast({
          message: '请输入门店名称',
          position: 'middle',
          duration: 800
        });
        return false;
      }
      if(this.post.linkName==''){
        Toast({
          message: '请输入联系人',
          position: 'middle',
          duration: 800
        });
        return false;
      }
      if(!myreg.test(this.post.linkPhone)){
        Toast({
          message: '请输入有效的手机号码',
          position: 'middle',
          duration: 800
        });
        return false;
      }
      if(this.post.code==''){
        Toast({
          message: '请输入验证码',
          position: 'middle',
          duration: 800
        });
        return false;
      }
      if(this.post.area==''){
        Toast({
          message: '请输入所在地区',
          position: 'middle',
          duration: 800
        });
        return false;
      }
      if(this.post.address==''){
        Toast({
          message: '请输入详细地址',
          position: 'middle',
          duration: 800
        });
        return false;
      }
      if(this.mediaAttr.length<=0){
        Toast({
          message: '请上传营业执照',
          position: 'middle',
          duration: 800
        });
        return false;
      }
      this.getOss();
      var that=this;
      that.post.licenseImgOss='';
      that.post.shopImgOss='';
      that.myUploads=[];

      for(var i=0;i<that.mediaAttr.length;i++){

        const mediaId = that.mediaAttr[i].serverId; // 微信多媒体文件id
        const fileLocate = that.mediaAttr[i].fileLocate; // 微信多媒体文件id
        const tag = that.mediaAttr[i].tag; // 微信多媒体文件id

        if(tag==''){
          Indicator.open({
            text: '申请提交中...',
            spinnerType: 'snake'
          });
          that.$axios({
            method: 'get',
            url:'wx/cgi-bin/media/get?access_token='+that.accessToken+'&media_id='+mediaId,
            responseType:'arraybuffer',
          }).then((res)=>{
            // arrayBuffer转Buffer
            var buffer = that.toBuffer(res.data);
          var destPath = 'erpStore/'+fileLocate+'/'+mediaId+'.jpg'; // OSS文件路径
          console.log(buffer)
          var postitem={}
          that.client.put(destPath, buffer).then((result) => {
            console.log('图片上传阿里云结果', result);
          var item='https://rmcbapp.oss-cn-shenzhen.aliyuncs.com/'+result.name;
          if(fileLocate=='营业执照'){
            if(that.post.licenseImgOss==''){
              that.post.licenseImgOss+=item;
            }else{
              that.post.licenseImgOss+=','+item;
            }
          }else if(fileLocate=='实体门店图'){

            if(that.post.shopImgOss==''){
              that.post.shopImgOss+=item;
            }else{
              that.post.shopImgOss+=','+item;
            }
          }
          that.myUploads.push(item);
          if(that.myUploads.length==i){

            if(this.post.licenseImgOss==''){
              Indicator.close();
              Toast({
                message: '请上传营业执照',
                position: 'middle',
                duration: 800
              });
              return false;
            }
            if(this.post.shopImgOss==''){
              Indicator.close();
              Toast({
                message: '请上传实体门店图',
                position: 'middle',
                duration: 800
              });
              return false;
            }
            var params = new URLSearchParams();
            params.append('form.storeName',this.post.storeName);
//            params.append('form.storeType',this.post.storeType);
            params.append('form.name',this.post.linkName);
            params.append('form.mobile',this.post.linkPhone);
            params.append('form.area',this.post.area);
            params.append('form.storeAddress',this.post.address);
            params.append('form.code',this.post.code);
            params.append('form.openId',this.post.openId);
            params.append('form.licenseImgOss',this.post.licenseImgOss)  ;
            params.append('form.shopImgOss',this.post.shopImgOss);
            that.$axios({
              method: 'post',
              url:'gp/bu/storeApply!saveApply.do',
              data:params
            }).then((res)=>{
              if(res.data.statusCode==200){
              console.log(res,11111)
              Indicator.close();
              this.popupApplyCorrect=true;
//              Toast({
//                message: '提交成功，请耐心等待审核！',
//                position: 'middle',
//                duration:1000
//              });
//              setTimeout(()=>{
//                window.location.reload();
//            },1000)
            }else{
              Indicator.close();
              Toast({
                message: res.data.message,
                position: 'middle',
                duration:1000
              });
            }
          }).catch((error)=> {
              Indicator.close();
            Toast({
              message: error,
              position: 'middle',
              duration:2000
            });
          });
          }

        }).catch((err) => {
            console.log(err)
          Toast({
            message: '图片上传失败',
            position: 'middle',
            duration:1000
          });
        });

        })
        }else{
          console.log('该图片已上传')
        }
      };
    },
  }
}
</script>
<style>
  .store-settled-in .popup-address{
    width: 100%;
    padding:10px 0 0;
  }

  .store-settled-in .picker-item{
    color:#999
  }
  .store-settled-in .picker-item.picker-selected{
    color:#007EE5
  }
  .store-settled-in .popup-address .button-content{
    padding:24px 40px;
  }
  .store-settled-in .popup-address .button-content .mint-button--normal{
    background: -webkit-linear-gradient(left, #03adf3 , #0080e5); /* Safari 5.1 - 6.0 */
    background: -o-linear-gradient(right, #03adf3 , #0080e5); /* Opera 11.1 - 12.0 */
    background: -moz-linear-gradient(right, #03adf3 , #0080e5); /* Firefox 3.6 - 15 */
    background: linear-gradient(to right, #03adf3 , #0080e5); /* 标准的语法 */
    width: 100%;
  }
  .store-settled-in .button-content-apply{
    padding:24px 32px;
  }
  .store-settled-in .button-content-apply .mint-button--normal{
    background: -webkit-linear-gradient(left, #03adf3 , #0080e5); /* Safari 5.1 - 6.0 */
    background: -o-linear-gradient(right, #03adf3 , #0080e5); /* Opera 11.1 - 12.0 */
    background: -moz-linear-gradient(right, #03adf3 , #0080e5); /* Firefox 3.6 - 15 */
    background: linear-gradient(to right, #03adf3 , #0080e5); /* 标准的语法 */
    width: 100%;
  }

  .store-settled-in .module-photo{
    padding:16px 0 0;
  }
  .store-settled-in .module-photo .addon{
    padding:0 12px ;
    font-size: 16px;
    color: #666;
  }
  .store-settled-in .img-upload-content{
    width:94%;
    margin: 0;
    padding:0 0 16px;
  }
  .store-settled-in .img-upload-content .item{
    position: relative;
    width:33.2% !important;
    height:60px;
    padding:0 12px 12px 0;
    margin:16px 0 0;
  }
  .store-settled-in .img-upload-content img{
    width: 100%;
    height: 60px;
  }
  .store-settled-in .img-upload-content .icon-shanchu{
    background:rgba(225,225,225,0.5) !important;
    position: absolute;
    top:0;
    right:12px;
    width: 20px;
    height: 20px;
    font-size:15px !important;
    color:#fff;
    text-align: center;
    line-height: 24px;
  }
  .store-settled-in .add-img{
    display: block;
    height: 60px;
    padding:0;
    color: #ddd;
    line-height: 60px;
    text-align: center;
    border:1px dashed #ddd;
  }
  .store-settled-in .add-img:before{
    display: block;
    margin:0 auto 4px;
    font-size: 24px;
  }
  .store-settled-in .select-operator{
    width: 100%;
    min-height:32px;
    border:none;
    outline:none;
    font-size: 16px;
    color: #666;
  }
  .store-settled-in .button-send-code{
    background: #007EE5;
    font-size: 15px;
    height:34px;
  }
  .store-settled-in .button-send-code.disabled{
    background: #999;
  }
  .store-settled-in .popup-apply-correct{
    width: 100%;
    height: 100%;
    padding:120px 0 0;
    text-align: center;
  }
  .store-settled-in .popup-apply-correct .icon-chenggong{
    color: #007EE5;
    font-size: 60px;
  }
  .store-settled-in .popup-apply-correct .correct-tips{
    padding:12px 0 0;
    font-size: 16px;
    color: #555;
  }
</style>
<!-- Add "scoped" attribute to limit CSS to this component only -->

